package com.zjitc.controller;

import com.zjitc.domain.MessageConstant;
import com.zjitc.domain.Result;
import com.zjitc.domain.ResultPage;
import com.zjitc.domain.User;
import com.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    //删除功能
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Integer id) {
        try {
            userService.removeById(id);
        } catch (Exception e) {
            return new Result(false, MessageConstant.DELETE_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS, null);
    }

    //添加功能
    @PostMapping
    public Result addUser(@RequestBody User user) {
        try {
            userService.save(user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.ADD_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS, null);
    }

    //按ID查找功能
    @GetMapping("/{id}")
    public User findById(@PathVariable("id") Integer id) {
        User user;
        try {
            user = userService.getById(id);
        } catch (Exception e) {
            return null;
        }
        return user;

    }

    //修改功能
    @PutMapping
    public Result update(@RequestBody User user) {
        try {
            userService.updateById(user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.EDIT_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.EDIT_USER_SUCCESS, null);
    }

    @PostMapping("/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize, @RequestBody User user) {

        ResultPage<User> page=null;
        try {
            page=userService.findPage(currentPage, pageSize, user);
        }catch (Exception e){
            return new Result(false, MessageConstant.QUERY_USER_FAIL, null);
        }

        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, page);    }

    @GetMapping
    public List<User> findAll(){
        return userService.list();
    }
}
